(function() {
    var s = {};
    //判断
    s.jinacha = function(third, callback) {
            // var weibo = api.require('weibo');
            var wx = api.require('wx');
            var weibo= api.require('weiboPlus');
            var qq = api.require('QQPlus');
            var systemType = api.systemType;

            if (third == 'weibo') {
                weibo.isInstalled(
                    function(ret) {
                        if (ret.status) {
                            if (typeof callback == 'function') {
                                callback()
                            }
                        } else {
                            if (systemType == 'ios') {
                                api.installApp({
                                    appUri: 'https://itunes.apple.com/cn/app/%E5%BE%AE%E5%8D%9A/id350962117?mt=8' //安装包对应plist地址
                                });
                            } else {
                              // api.openApp({
                              //  androidPkg : 'android.intent.action.VIEW',
                              //  mimeType : 'text/html',
                              //  uri : 'https://android.myapp.com/myapp/detail.htm?apkName=com.sina.weibo&ADTAG=mobile'
                              //  }, function(ret, err) {
                              //
                              //  });
                              api.openWin({
                                  name: 'down',
                                  url: '../VIP/down.html',
                                  pageParam: {
                                      url: 'https://android.myapp.com/myapp/detail.htm?apkName=com.sina.weibo&ADTAG=mobile'
                                  }
                              });
                            }
                            // api.toast({
                            //     msg: '请先安装微博客户端',
                            //     duration: 2000,
                            //     location: 'middle'
                            // });

                            // callback(false)
                        }
                    }
                );
            } else if (third == 'qq') {
                qq.installed(function(ret, err) {
                    if (ret.status) {
                        if (typeof callback == 'function') {
                            callback()
                        }
                    } else {
                        if (systemType == 'ios') {
                            api.installApp({
                                appUri: 'https://itunes.apple.com/cn/app/qq/id444934666?mt=8' //安装包对应plist地址
                            });
                        } else {
                          // api.openApp({
                          //  androidPkg : 'android.intent.action.VIEW',
                          //  mimeType : 'text/html',
                          //  uri : 'https://android.myapp.com/myapp/detail.htm?apkName=com.tencent.mobileqq&ADTAG=mobile'
                          //  }, function(ret, err) {
                          //
                          //  });
                          api.openWin({
                              name: 'down',
                              url: '../VIP/down.html',
                              pageParam: {
                                  url: 'https://android.myapp.com/myapp/detail.htm?apkName=com.tencent.mobileqq&ADTAG=mobile'
                              }
                          });

                        }
                        // api.toast({
                        //     msg: '请先安装qq客户端',
                        //     duration: 2000,
                        //     location: 'middle'
                        // });
                        // callback(false)
                    }
                });
            } else if (third == 'wx') {

                wx.isInstalled(function(ret, err) {
                    if (ret.installed) {
                        if (typeof callback == 'function') {
                            callback()
                        }
                    } else {
                        if (systemType == 'ios') {
                            api.installApp({
                                appUri: 'https://itunes.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id414478124?mt=8' //安装包对应plist地址
                            });
                        } else {
                          // api.openApp({
                          //  androidPkg : 'android.intent.action.VIEW',
                          //  mimeType : 'text/html',
                          //  uri : 'https://android.myapp.com/myapp/detail.htm?apkName=com.tencent.mm&ADTAG=mobile'
                          //  }, function(ret, err) {
                          //
                          //  });
                          api.openWin({
                              name: 'down',
                              url: '../VIP/down.html',
                              pageParam: {
                                  url: 'https://android.myapp.com/myapp/detail.htm?apkName=com.tencent.mm&ADTAG=mobile'
                              }
                          });

                        }
                        // api.toast({
                        //     msg: '请先安装微信客户端',
                        //     duration: 2000,
                        //     location: 'middle'
                        // });
                        // callback(false)
                    }
                });
            }

        }
        //第三获取信息
    s.auth = function(third, callback, islogin, error) {
            var weibo = api.require('weiboPlus');
            var wx = api.require('wx');
            var qq = api.require('QQPlus');
            s.jinacha(third, function(ret) {
                if (typeof callback == 'function') {
                    if (!ret) {
                        if (typeof weiyou == 'function') {
                            error(third)
                        }
                    }
                    if (third == 'weibo') {
                        weibo.auth(function(ret, err) {
                            // alert(JSON.stringify(ret));
                            if (ret.status) {
                                $api.setStorage('weiboid', ret.userId);
                                //获取微博信息
                                weibo.getUserInfo({
                                    token: ret.token,
                                    userId: ret.userId
                                }, function(ret2, err2) {
                                    if (ret2.status) {
                                      $api.setStorage('third_headimgurl', ret2.userInfo.profile_image_url);
                                        s.iscunzai(third, ret.userId, callback, ret2.userInfo.name);
                                        // s.thirdregister(third, ret.userId, callback,ret2.userInfo.name,ret2.userInfo.profile_image_url);
                                        // alert(JSON.stringify(ret2.userInfo));
                                        console.log(JSON.stringify(ret2.userInfo));
                                    }
                                });
                            }
                            // alert(JSON.stringify(ret));
                            // callback(ret, err)
                        });
                    } else if (third == 'qq') {
                        qq.login(function(ret, err) {
                            if (ret.status) {
                                $api.setStorage('qqopenid', ret.openId);
                                qq.getUserInfo(function(ret2, err2) {
                                    console.log(JSON.stringify(ret2.info))
                                    if (typeof(ret2.info) == 'string') {
                                        var qqresult = JSON.parse(ret2.info);
                                    } else {
                                        var qqresult = ret2.info;
                                    }
                                    if (ret2.status) {
                                        $api.setStorage('third_headimgurl', qqresult.figureurl_qq_2);
                                        s.iscunzai(third, ret.openId, callback, qqresult.nickname);
                                        // if (islogin) {
                                        //     s.thirdregister(third, ret.openId, callback,ret2.info.nickname,ret2.info.figureurl_qq_2);
                                        // } else {
                                        //   callback(ret.openId)
                                        // }
                                    } else {
                                        api.toast({
                                            msg: '获取个人信息失败',
                                            duration: 2000,
                                            location: 'middle'
                                        });
                                    }
                                });
                            } else {
                                if (typeof error == 'function') {
                                    error(third)
                                }
                            }
                        })
                    } else if (third == 'wx') {
                        if (typeof error == 'function') {
                            error(third)
                        }
                        wx.auth({
                            apiKey: ''
                        }, function(ret, err) {
                            wx.getToken({
                                apiKey: '',
                                apiSecret: '',
                                code: ret.code
                            }, function(ret2, err2) {
                                if (ret2.status) { //获取用户信息
                                    wx.getUserInfo({
                                        accessToken: ret2.accessToken,
                                        openId: ret2.openId
                                    }, function(ret3, err) {
                                        if (ret3.status) {
                                            s.iscunzai(third, ret3.openid, callback, ret3.nickname);
                                            $api.setStorage('wxopenid', ret3.openid);
                                            $api.setStorage('third_nickname', ret3.nickname);
                                            $api.setStorage('third_headimgurl', ret3.headimgurl);
                                            // if (islogin) {
                                            //     s.thirdregister(third, ret3.openid, callback,ret3.nickname,ret3.headimgurl);
                                            // } else {
                                            //   callback(ret3.openid)
                                            // }
                                        } else {
                                            api.toast({
                                                msg: '获取用户信息',
                                                duration: 2000,
                                                location: 'middle'
                                            });
                                        }
                                    });
                                    //获取用户信息end
                                } else {
                                    if (typeof error == 'function') {
                                        error(third)
                                    }
                                }
                            });

                        });
                    }
                }
            })
        }
        // 查第三方是否存在
    s.iscunzai = function(third, thirdopenid, callback, uname) {
        if (third == 'wx') {
            third = 'weixin'
        }
        var data = {};
        data[third] = thirdopenid;

        new rest().get('getUserInfoThird').datae(data).success(function(res) {
            if (typeof callback == 'function') {
                callback(res, third, thirdopenid, uname)
            }
        }).error(function(err) {
            api.toast({
                msg: err.msg,
                duration: 2000,
                location: 'center'
            });
        }).run()
    }

    //第三方注册
    s.thirdregister = function(third, openId, callback, uname, uavatar) {
        if (third == 'wx') {
            third = 'weixin'
        }
        // alert(uname)
        var data = {};
        var deviceId = api.deviceId;
        data['device_id'] = deviceId;
        data[third] = openId;
        if (third == 'weixin') {
            data['wxname'] = uname
        } else if (third == 'qq') {
            data['qqname'] = uname
        } else if (third == 'weibo') {
            data['weiboname'] = uname
        }

        new rest().get('registerThird').datae(data).success(function(res) {
            if (third == 'weixin') {
                console.log('绑定微信')
                $api.setStorage('bdwx', true);
            } else if (third == 'qq') {
                console.log('绑定qq')
                $api.setStorage('bdqq', true);
            } else if (third == 'weibo') {
                console.log('绑定微博')
                $api.setStorage('bdwb', true);
            }
            s.thirdlogin(third, openId, callback, uname, uavatar)
        }).error(function(err) {
            api.toast({
                msg: err.msg,
                duration: 2000,
                location: 'center'
            });
        }).run()
    }

    //第三方登录
    s.thirdlogin = function(third, restopenid, callback) {
        var data = {};
        var deviceId = api.deviceId;
        data['device_id'] = deviceId;
        data[third] = restopenid
        new rest().get('loginThird').datae(data).success(function(res) {
            if (typeof callback == 'function') {
                callback(res)
            }
        }).error(function(err) {
            api.toast({
                msg: err.msg,
                duration: 2000,
                location: 'center'
            });
        }).run()
    }


    //第三方解绑//obj是wxopenid，wbopenid，qqopenid //thirdtype是weixin qq 和weibo
    s.unlockThird = function(third, callback) {
        var data = {},
            openid;
        if (third == 'wx') {
            third = 'weixin'
            openid = $api.getStorage('wxopenid');
        } else if (third == 'qq') {
            openid = $api.getStorage('qqopenid');
        } else {
            openid = $api.getStorage('wbopenid');
        }
        // data['session'] = $api.getStorage('session');
        data['uid'] = $api.getStorage('uid');
        data[third] = openid;
        // alert(JSON.stringify(data))
        new rest().get('unlockThird').datae(data).success(function(res) {
            if (typeof callback == 'function') {
                callback(res)
            }
        }).error(function(err) {
            api.toast({
                msg: err.msg,
                duration: 2000,
                location: 'center'
            });
        }).run()
    }
    s.unlockThird2 = function(uid, type, callback) {
        var data = {};
        data['uid'] = uid;
        data[type] = 1,
            // alert(JSON.stringify(data))
            new rest().get('unlockThird').datae(data).success(function(res) {
                if (typeof callback == 'function') {
                    callback(res)
                }
            }).error(function(err) {
                api.toast({
                    msg: err.msg,
                    duration: 2000,
                    location: 'center'
                });
            }).run()
    }
    s.userinfornation = function(avatarurl, nickname) {
            var session = $api.getStorage('session');
            var uid = $api.getStorage('uid');
            api.download({
                url: avatarurl,
                savePath: '',
                report: true,
                cache: true,
                allowResume: true
            }, function(ret, err) {
                if (ret.state == 1) {
                    var avatarUrl_ = ret.savePath;
                    api.ajax({
                        url: config.apiHost + config.restRoute.uploadPic,
                        method: 'post',
                        data: {
                            values: {
                                _uid: uid,
                                session: session
                            },
                            files: {
                                file: avatarUrl_
                            }
                        }
                    }, function(ret, err) {

                    });
                } else {

                }
            });
        }
        //第三方分享ortype session（会话）timeline（朋友圈）favorite（收藏）
    s.shareurl = function(thirdtype, ortype, url, title, description, imgurl, callback,callback1) {
        s.jinacha(thirdtype, function() {
            if (thirdtype == 'qq') {
              if (typeof callback == 'function') {
                  callback(1,0)
              }
                var qq = api.require('QQPlus');
                qq.shareNews({
                    type: ortype,
                    url: url,
                    title: title,
                    description: description,
                    imgUrl: imgurl
                }, function(ret, err) {
                  if (typeof callback == 'function') {
                      callback1(ret,err)
                  }
                    // alert('qq安卓版应用还未提交审核')
                });
            } else if (thirdtype == 'wx') {
              if (typeof callback == 'function') {
                  callback(1,0)
              }
                var wx = api.require('wx');
                wx.shareWebpage({
                    apiKey: '',
                    scene: ortype,
                    title: title,
                    description: description,
                    thumb: 'widget://image/sharelogo.png',
                    contentUrl: url
                }, function(ret, err) {
                  if (typeof callback == 'function') {
                      callback1(ret,err)
                  }
                });
            } else if (thirdtype == 'weibo') {
              if (typeof callback == 'function') {
                  callback(1,0)
              }
                var weibo = api.require('weiboPlus');
                weibo.shareWebPage({
                    text: title,
                    title: title,
                    description: description,
                    thumb: 'widget://image/sharelogo.png',
                    contentUrl: url
                }, function(ret, err) {
                  if (typeof callback == 'function') {
                      callback1(ret,err)
                  }
                });
            }
        })
    }

    window.third = s;
})(window)
